package com.goblin.model.film.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import javax.annotation.Resource;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.goblin.common.response.PageHelper;
import com.goblin.common.response.Paged;
import com.goblin.model.film.po.Comment;
import com.goblin.model.film.po.Film;
import com.goblin.model.film.repository.CommentRepository;
import com.goblin.model.film.repository.FilmRepository;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
public class FilmServiceImpl implements FilmService {

	@Autowired
	private FilmRepository filmRepository;

	@Autowired
	private CommentRepository commentRepository;

	@Autowired
	private RestTemplate restTemplate;

	@Resource(name = "defaultThreadPool")
	private ThreadPoolTaskExecutor executor;

	private static final Logger logger = LoggerFactory.getLogger(FilmServiceImpl.class);

	@Override
	public Paged<Film> paged(PageHelper pageable) {
		return this.filmRepository.paged(pageable);
	}

	@Override
	public void searchFilm(Integer time) {

		this.executor.submit(() -> {
			//	入口
			String entryUrl = "https://movie.douban.com/j/search_subjects?"
					+ "type=movie&tag=热门&sort=rank&page_limit=100&page_start=";

			int pageStart = 0;

			boolean flag = true;

			long currentTime = System.currentTimeMillis();
			currentTime += time * 60 * 1000;

			while (flag) {
				long current = System.currentTimeMillis();
				if (current > currentTime) {
					flag = false;
				}
				pageStart *= 100;
				String url = entryUrl + pageStart;
				HttpHeaders headers = new HttpHeaders();
				String userAgent = "Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.87 Safari/537.36";

				headers.add("User-Agent", userAgent);
				HttpEntity<Resource> httpEntity = new HttpEntity<>(headers);

				ResponseEntity<String> responseEntity = this.restTemplate
						.exchange(url, HttpMethod.GET, httpEntity, String.class);
				JSONObject result = JSONObject.parseObject(responseEntity.getBody());
				logger.debug(result.toJSONString());
				JSONArray subjects = result.getJSONArray("subjects");
				for (int i = 0; i < subjects.size(); i++) {
					JSONObject subject = (JSONObject) subjects.get(i);

					Film film = new Film();
					film.setGrade(subject.getString("rate"));
					film.setFilmName(subject.getString("title"));
					film.setUrl(subject.getString("url"));
					film.setPost(subject.getString("cover"));

					String html = doGet(subject.getString("url")).getBody();

					Document htmlDoc = Jsoup.parse(html);
					Element wrapper = htmlDoc.getElementById("wrapper");

					try {
						//获取film内容
						film = gainFilm(wrapper, film);

						Optional<Film> optional = this.filmRepository
								.findFilmByFilmNameAndDirecter(film.getFilmName(),
										film.getDirecter());

						if (optional.isPresent()) {
							logger.debug("电影名：{}, 已保存", film.getTitle());
							continue;
						}

						film = this.filmRepository.save(film);

						//	获取comment内容
						List<Comment> comments = gainComment(wrapper, film);

						this.commentRepository.saveAll(comments);

						logger.debug("电影名: {}， 评论数:", film.getTitle(), comments.size());
					}
					catch (Exception ex) {

					}
				}

			}
		});

	}

	private Film gainFilm(Element wrapper, Film film) {

		Element content = wrapper.getElementById("content");
		Element h1 = content.getElementsByTag("h1").first();
		Element title1 = h1.getElementsByTag("span").first();
		Element title2 = h1.getElementsByTag("span").last();
		film.setTitle(title1.ownText() + title2.ownText());

		Elements list1 = content.getElementsByClass("grid-16-8 clearfix");
		Elements info = list1.first().getElementsByClass("article").first().
				getElementsByClass("indent clearfix").first()
				.getElementsByClass("subjectwrap clearfix").first()
				.getElementsByClass("subject clearfix").first().getElementById("info")
				.getElementsByTag("span");

		int index = 0;
		//=====================================获取导演===================================
		Element directorElements = info.get(index).getElementsByClass("attrs").first();
		Elements directorElements1 = directorElements.getElementsByTag("a");

		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < directorElements1.size(); i++) {
			sb.append(directorElements1.get(i).ownText());
			sb.append("/");
		}

		film.setDirecter(sb.toString());

		index = 6;
		//=====================================获取演员===================================
		Element actorElements = info.get(index).getElementsByClass("attrs").first();
		Elements actorElements1 = actorElements.getElementsByTag("a");

		sb.delete(0, sb.length());
		for (int i = 0; i < actorElements1.size(); i++) {
			sb.append(actorElements1.get(i).ownText());
			sb.append("/");
		}

		film.setActors(sb.toString());

		index = 10;
		//=====================================获取类型===================================
		Elements typeEle1 = info.get(index).getElementsByTag("span");
		++index;
		Elements typeEle2 = info.get(index).getElementsByTag("span");
		++index;
		Elements typeEle3 = info.get(index).getElementsByTag("span");

		sb.delete(0, sb.length());
		sb.append(typeEle1.first().ownText());
		sb.append("/");
		sb.append(typeEle2.first().ownText());
		sb.append("/");
		if (typeEle3.first().ownText().equals("官方网站:")) {
			--index;
		}
		else {
			sb.append(typeEle3.first().ownText());
			sb.append("/");
		}

		film.setType(sb.toString());

		return film;
	}

	private List<Comment> gainComment(Element wrapper, Film film) {

		List<Comment> list = new ArrayList();
		Comment comment = null;

		Element content = wrapper.getElementById("content");
		Element content1 = content.getElementsByClass("grid-16-8 clearfix").first();
		Element content2 = content1.getElementsByClass("article").first();
		Element content3 = content2.getElementById("comments-section");
		Element content4 = content3.getElementsByClass("mod-bd").first();
		Element content5 = content4.getElementsByClass("tab-bd").first();
		Element content6 = content5.getElementById("hot-comments");
		Element aEle = content6.getElementsByTag("a").last();

		Document htmlDoc = Jsoup
				.parse(doGet(film.getUrl() + aEle.attr("href") + "&start=0&limit=100")
						.getBody());
		Element wrapperE = htmlDoc.getElementById("wrapper");

		Element c1 = wrapperE.getElementById("content");
		Element c2 = c1.getElementsByClass("grid-16-8 clearfix").first();
		Element c3 = c2.getElementsByClass("article").first();
		Element c4 = c3.getElementById("comments");
		Elements c5 = c4.getElementsByClass("comment-item");

		for (int i = 0; i < c5.size(); i++) {
			String c6 = c5.get(i).getElementsByClass("avatar").first()
					.getElementsByTag("a").first().attr("title");
			comment = new Comment();
			comment.setName(c6);
			comment.setFilm(film);

			String c7 = c5.get(i).getElementsByClass("comment").first()
					.getElementsByClass("comment-content").first()
					.getElementsByClass("short").first().ownText();
			comment.setContent(c7);

			String c8 = c5.get(i).getElementsByClass("comment").first()
					.getElementsByTag("h3").first().getElementsByClass("comment-vote")
					.first().getElementsByClass("votes vote-count").first().ownText();
			comment.setLikes(c8);

			String c9 = c5.get(i).getElementsByClass("comment").first()
					.getElementsByTag("h3").first().getElementsByClass("comment-info")
					.first().getElementsByClass("comment-time").first().attr("title");
			comment.setDate(c9);

			list.add(comment);
		}

		return list;
	}

	private ResponseEntity<String> doGet(String url) {
		HttpHeaders headers = new HttpHeaders();
		headers.add("user-agent",
				"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36");
		HttpEntity<Resource> httpEntity = new HttpEntity<Resource>(headers);

		ResponseEntity<String> responseEntity = this.restTemplate
				.exchange(url, HttpMethod.GET, httpEntity, String.class);
		return responseEntity;
	}
}
